using System;
using System.Drawing;
using System.Windows.Forms;
using System.Linq;

namespace StarSkipGame
{
    /// <summary>
    /// 游戏统计窗体
    /// </summary>
    public partial class StatisticsForm : Form
    {
        private GameEngine gameEngine;
        private TabControl tabControl;
        private Button btnClose;
        private Button btnReset;

        // 总体统计控件
        private Label lblTotalGames;
        private Label lblTotalPlayTime;
        private Label lblAverageSurvivalTime;
        private Label lblBestScore;
        private Label lblTotalAsteroidsAvoided;
        private Label lblAchievementsUnlocked;

        // 高分记录控件
        private ListView lvwHighScores;
        private ComboBox cboHighScoreMode;

        // 成就统计控件
        private ListView lvwAchievements;
        private ProgressBar prgOverallProgress;
        private Label lblOverallProgress;

        // 游戏模式统计控件
        private ListView lvwGameModeStats;

        public StatisticsForm(GameEngine engine)
        {
            gameEngine = engine;
            InitializeComponent();
            LoadStatistics();
        }

        private void InitializeComponent()
        {
            this.Text = "游戏统计";
            this.Size = new Size(700, 600);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            // 创建主布局
            tabControl = new TabControl();
            tabControl.Dock = DockStyle.Top;
            tabControl.Size = new Size(680, 520);

            // 创建选项卡
            CreateOverviewTab();
            CreateHighScoresTab();
            CreateAchievementsTab();
            CreateGameModeTab();

            // 创建按钮
            CreateButtons();

            // 添加控件到窗体
            this.Controls.Add(tabControl);
            this.Controls.Add(btnClose);
            this.Controls.Add(btnReset);

            // 设置按钮位置
            btnClose.Location = new Point(580, 540);
            btnReset.Location = new Point(20, 540);
        }

        private void CreateOverviewTab()
        {
            TabPage overviewTab = new TabPage("总体统计");
            overviewTab.Padding = new Padding(10);

            // 创建统计标签
            lblTotalGames = new Label();
            lblTotalGames.Location = new Point(20, 20);
            lblTotalGames.Size = new Size(300, 20);
            lblTotalGames.Font = new Font("Microsoft YaHei", 10);

            lblTotalPlayTime = new Label();
            lblTotalPlayTime.Location = new Point(20, 50);
            lblTotalPlayTime.Size = new Size(300, 20);
            lblTotalPlayTime.Font = new Font("Microsoft YaHei", 10);

            lblAverageSurvivalTime = new Label();
            lblAverageSurvivalTime.Location = new Point(20, 80);
            lblAverageSurvivalTime.Size = new Size(300, 20);
            lblAverageSurvivalTime.Font = new Font("Microsoft YaHei", 10);

            lblBestScore = new Label();
            lblBestScore.Location = new Point(20, 110);
            lblBestScore.Size = new Size(300, 20);
            lblBestScore.Font = new Font("Microsoft YaHei", 10);

            lblTotalAsteroidsAvoided = new Label();
            lblTotalAsteroidsAvoided.Location = new Point(20, 140);
            lblTotalAsteroidsAvoided.Size = new Size(300, 20);
            lblTotalAsteroidsAvoided.Font = new Font("Microsoft YaHei", 10);

            lblAchievementsUnlocked = new Label();
            lblAchievementsUnlocked.Location = new Point(20, 170);
            lblAchievementsUnlocked.Size = new Size(300, 20);
            lblAchievementsUnlocked.Font = new Font("Microsoft YaHei", 10);

            // 添加控件到选项卡
            overviewTab.Controls.AddRange(new Control[] 
            {
                lblTotalGames, lblTotalPlayTime, lblAverageSurvivalTime,
                lblBestScore, lblTotalAsteroidsAvoided, lblAchievementsUnlocked
            });

            tabControl.TabPages.Add(overviewTab);
        }

        private void CreateHighScoresTab()
        {
            TabPage highScoresTab = new TabPage("高分记录");
            highScoresTab.Padding = new Padding(10);

            // 游戏模式选择
            Label lblMode = new Label();
            lblMode.Text = "选择游戏模式:";
            lblMode.Location = new Point(20, 20);
            lblMode.Size = new Size(120, 20);

            cboHighScoreMode = new ComboBox();
            cboHighScoreMode.Location = new Point(150, 20);
            cboHighScoreMode.Size = new Size(200, 25);
            cboHighScoreMode.DropDownStyle = ComboBoxStyle.DropDownList;
            cboHighScoreMode.Items.AddRange(new object[] 
            {
                "所有模式", "经典模式", "生存模式", "时间挑战模式", "无尽模式", "Boss挑战模式"
            });
            cboHighScoreMode.SelectedIndex = 0;
            cboHighScoreMode.SelectedIndexChanged += CboHighScoreMode_SelectedIndexChanged;

            // 高分列表
            lvwHighScores = new ListView();
            lvwHighScores.Location = new Point(20, 60);
            lvwHighScores.Size = new Size(620, 400);
            lvwHighScores.View = View.Details;
            lvwHighScores.FullRowSelect = true;
            lvwHighScores.GridLines = true;

            // 添加列
            lvwHighScores.Columns.Add("排名", 60);
            lvwHighScores.Columns.Add("玩家", 100);
            lvwHighScores.Columns.Add("生存时间", 100);
            lvwHighScores.Columns.Add("敌人数量", 80);
            lvwHighScores.Columns.Add("游戏模式", 120);
            lvwHighScores.Columns.Add("日期", 150);

            // 添加控件到选项卡
            highScoresTab.Controls.AddRange(new Control[] 
            {
                lblMode, cboHighScoreMode, lvwHighScores
            });

            tabControl.TabPages.Add(highScoresTab);
        }

        private void CreateAchievementsTab()
        {
            TabPage achievementsTab = new TabPage("成就统计");
            achievementsTab.Padding = new Padding(10);

            // 总体进度
            Label lblProgress = new Label();
            lblProgress.Text = "总体进度:";
            lblProgress.Location = new Point(20, 20);
            lblProgress.Size = new Size(100, 20);

            prgOverallProgress = new ProgressBar();
            prgOverallProgress.Location = new Point(130, 20);
            prgOverallProgress.Size = new Size(300, 20);

            lblOverallProgress = new Label();
            lblOverallProgress.Location = new Point(440, 20);
            lblOverallProgress.Size = new Size(100, 20);

            // 成就列表
            lvwAchievements = new ListView();
            lvwAchievements.Location = new Point(20, 60);
            lvwAchievements.Size = new Size(620, 400);
            lvwAchievements.View = View.Details;
            lvwAchievements.FullRowSelect = true;
            lvwAchievements.GridLines = true;

            // 添加列
            lvwAchievements.Columns.Add("成就", 200);
            lvwAchievements.Columns.Add("描述", 250);
            lvwAchievements.Columns.Add("状态", 80);
            lvwAchievements.Columns.Add("解锁日期", 120);

            // 添加控件到选项卡
            achievementsTab.Controls.AddRange(new Control[] 
            {
                lblProgress, prgOverallProgress, lblOverallProgress, lvwAchievements
            });

            tabControl.TabPages.Add(achievementsTab);
        }

        private void CreateGameModeTab()
        {
            TabPage gameModeTab = new TabPage("游戏模式统计");
            gameModeTab.Padding = new Padding(10);

            // 游戏模式统计列表
            lvwGameModeStats = new ListView();
            lvwGameModeStats.Location = new Point(20, 20);
            lvwGameModeStats.Size = new Size(620, 440);
            lvwGameModeStats.View = View.Details;
            lvwGameModeStats.FullRowSelect = true;
            lvwGameModeStats.GridLines = true;

            // 添加列
            lvwGameModeStats.Columns.Add("游戏模式", 150);
            lvwGameModeStats.Columns.Add("游戏次数", 100);
            lvwGameModeStats.Columns.Add("最佳分数", 100);
            lvwGameModeStats.Columns.Add("平均生存时间", 120);
            lvwGameModeStats.Columns.Add("总躲避陨石", 100);
            lvwGameModeStats.Columns.Add("完成率", 80);

            // 添加控件到选项卡
            gameModeTab.Controls.Add(lvwGameModeStats);

            tabControl.TabPages.Add(gameModeTab);
        }

        private void CreateButtons()
        {
            btnClose = new Button();
            btnClose.Text = "关闭";
            btnClose.Size = new Size(75, 30);
            btnClose.Click += BtnClose_Click;

            btnReset = new Button();
            btnReset.Text = "重置统计";
            btnReset.Size = new Size(100, 30);
            btnReset.Click += BtnReset_Click;
        }

        private void LoadStatistics()
        {
            LoadOverviewStatistics();
            LoadHighScores();
            LoadAchievements();
            LoadGameModeStatistics();
        }

        private void LoadOverviewStatistics()
        {
            var settings = GameSettings.Instance;
            var highScoreManager = gameEngine.HighScoreManager;
            var achievementSystem = gameEngine.AchievementSystem;

            // 计算总体统计
            int totalGames = gameEngine.GamesPlayed;
            float totalPlayTime = highScoreManager.GetAllHighScores().Sum(hs => hs.Score);
            float averageSurvivalTime = totalGames > 0 ? totalPlayTime / totalGames : 0;
            float bestScore = highScoreManager.GetAllHighScores().Count > 0 ? 
                highScoreManager.GetAllHighScores().Max(hs => hs.Score) : 0;
            int totalEnemiesSpawned = highScoreManager.GetAllHighScores().Sum(hs => hs.TotalEnemies);
            int achievementsUnlocked = achievementSystem.GetUnlockedAchievements().Count;

            // 更新标签
            lblTotalGames.Text = string.Format("总游戏次数: {0}", totalGames);
            lblTotalPlayTime.Text = string.Format("总游戏时间: {0:F1} 秒", totalPlayTime);
            lblAverageSurvivalTime.Text = string.Format("平均生存时间: {0:F1} 秒", averageSurvivalTime);
            lblBestScore.Text = string.Format("最高生存时间: {0:F1} 秒", bestScore);
            lblTotalAsteroidsAvoided.Text = string.Format("总敌人数量: {0}", totalEnemiesSpawned);
            lblAchievementsUnlocked.Text = string.Format("已解锁成就: {0}/{1}", 
                achievementsUnlocked, achievementSystem.GetAllAchievements().Count);
        }

        private void LoadHighScores()
        {
            lvwHighScores.Items.Clear();
            var highScores = gameEngine.HighScoreManager.GetAllHighScores();

            // 根据选择的模式过滤
            if (cboHighScoreMode.SelectedIndex > 0)
            {
                string selectedMode = cboHighScoreMode.SelectedItem.ToString();
                highScores = highScores.Where(hs => hs.GameMode == selectedMode).ToList();
            }

            // 按分数排序
            highScores = highScores.OrderByDescending(hs => hs.Score).Take(20).ToList();

            for (int i = 0; i < highScores.Count; i++)
            {
                var score = highScores[i];
                var item = new ListViewItem((i + 1).ToString());
                            item.SubItems.Add(score.PlayerName);
            item.SubItems.Add(string.Format("{0:F1}s", score.Score));
            item.SubItems.Add(score.TotalEnemies.ToString());
            item.SubItems.Add(score.GameMode);
            item.SubItems.Add(score.Date.ToString("yyyy-MM-dd HH:mm"));

                lvwHighScores.Items.Add(item);
            }
        }

        private void LoadAchievements()
        {
            lvwAchievements.Items.Clear();
            var achievements = gameEngine.AchievementSystem.GetAllAchievements();

            foreach (var achievement in achievements)
            {
                var item = new ListViewItem(achievement.Name);
                item.SubItems.Add(achievement.Description);
                item.SubItems.Add(achievement.IsUnlocked ? "已解锁" : "未解锁");
                item.SubItems.Add(achievement.IsUnlocked ? 
                    achievement.UnlockDate.ToString("yyyy-MM-dd HH:mm") : "-");

                if (achievement.IsUnlocked)
                {
                    item.BackColor = Color.LightGreen;
                }

                lvwAchievements.Items.Add(item);
            }

            // 更新总体进度
            int unlockedCount = achievements.Count(a => a.IsUnlocked);
            int totalCount = achievements.Count;
            int progressPercentage = totalCount > 0 ? (unlockedCount * 100) / totalCount : 0;

            prgOverallProgress.Value = progressPercentage;
            lblOverallProgress.Text = string.Format("{0}/{1} ({2}%)", 
                unlockedCount, totalCount, progressPercentage);
        }

        private void LoadGameModeStatistics()
        {
            lvwGameModeStats.Items.Clear();
            var highScores = gameEngine.HighScoreManager.GetAllHighScores();

            // 按游戏模式分组统计
            var modeStats = highScores.GroupBy(hs => hs.GameMode)
                .Select(g => new
                {
                    Mode = g.Key,
                    GamesPlayed = g.Count(),
                    BestScore = g.Max(hs => hs.Score),
                    AverageTime = g.Average(hs => hs.Score),
                    TotalEnemies = g.Sum(hs => hs.TotalEnemies) // 实际敌人数量
                }).ToList();

            foreach (var stat in modeStats)
            {
                var item = new ListViewItem(stat.Mode);
                item.SubItems.Add(stat.GamesPlayed.ToString());
                item.SubItems.Add(string.Format("{0:F1}s", stat.BestScore));
                item.SubItems.Add(string.Format("{0:F1}s", stat.AverageTime));
                item.SubItems.Add(stat.TotalEnemies.ToString());
                item.SubItems.Add(string.Format("{0:F1}%", 
                    stat.GamesPlayed > 0 ? (stat.GamesPlayed * 100.0 / gameEngine.GamesPlayed) : 0));

                lvwGameModeStats.Items.Add(item);
            }
        }

        private void CboHighScoreMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadHighScores();
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void BtnReset_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要重置所有游戏统计吗？此操作不可撤销！", "确认重置", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                // 重置高分记录
                gameEngine.HighScoreManager.ClearAllHighScores();
                
                // 重置成就
                gameEngine.AchievementSystem.ResetAllAchievements();
                
                // 重新加载统计
                LoadStatistics();
                
                MessageBox.Show("游戏统计已重置！", "重置完成", 
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
} 